import axios from 'axios'

// 创建axios实例
const api = axios.create({
  baseURL: 'http://localhost:8000/api/v1',
  timeout: 300000, // 300s
  headers: {
    'Content-Type': 'application/json'
  }
})

// 请求拦截器 - 添加token
api.interceptors.request.use(
  config => {
    const token = localStorage.getItem('access_token')
    if (token) {
      config.headers.Authorization = `Bearer ${token}`
    }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

// 响应拦截器 - 处理错误
api.interceptors.response.use(
  response => {
    // 统一处理响应数据结构
    const responseData = response.data
    
    // 如果响应数据包含标准字段，直接返回
    if (responseData && (responseData.success !== undefined || responseData.status !== undefined)) {
      return responseData
    }
    
    // 如果响应数据是数组或其他格式，包装成标准格式
    return {
      success: true,
      data: responseData,
      message: '请求成功'
    }
  },
  error => {
    if (error.response?.status === 401) {
      // token过期，跳转到登录页
      localStorage.removeItem('access_token')
      localStorage.removeItem('refresh_token')
      localStorage.removeItem('user_info')
      window.location.href = '/login'
    }
    return Promise.reject(error)
  }
)

// 认证相关API
export const authAPI = {
  login: (credentials) => api.post('/auth/login', credentials),
  register: (userData) => api.post('/auth/register', userData),
  refresh: (refreshToken) => api.post('/auth/refresh', { refresh_token: refreshToken })
}

// 用户相关API
export const userAPI = {
  getProfile: () => api.get('/users/profile'),
  updateProfile: (userData) => api.put('/users/profile', userData)
}

// 负荷数据相关API
export const loadDataAPI = {
  getByDate: (date) => api.get(`/load/date/${date}`),
  getByPeriod: (startDate, endDate) => api.get('/load/period', {
    params: { start_date: startDate, end_date: endDate }
  })
}

// 预测分析相关API
export const predictionAPI = {
  // 新版单日预测API - 支持模型选择
  getSingleDayPrediction: (params) => api.get('/prediction/single-day-prediction', { 
    params: {
      target_date: params.target_date,
      model: params.model
    }
  }),
  
  // 预测总览
  getPredictionOverview: (params) => api.get('/prediction/prediction-overview', { params }),
  
  // 模型训练
  trainModels: (params) => api.post('/model/train', params),
  
  // 增强训练API
  startEnhancedTraining: (params) => api.post('/enhanced-training/train/start', params),
  getEnhancedTrainingStatus: () => api.get('/enhanced-training/train/status'),
  getEnhancedTrainingResults: () => api.get('/enhanced-training/train/results'),
  getModelInterpretability: (modelName) => api.get(`/enhanced-training/train/interpretability/${modelName}`),
  stopEnhancedTraining: () => api.post('/enhanced-training/train/stop'),
  
  // 模型状态
  getModelStatus: () => api.get('/prediction/model-status'),
  
  // 历史数据查询
  getHistoricalData: (date, type) => api.get('/prediction/historical-data', {
    params: { date, type }
  }),
  getHistoricalRangeData: (startDate, endDate, type) => api.get('/prediction/historical-range', {
    params: { start_date: startDate, end_date: endDate, type }
  }),
  
  // 历史数据导出
  exportHistoricalData: (params) => api.get('/prediction/historical-load-details', {
    params: {
      start_date: params.start_date,
      end_date: params.end_date
    }
  }),
  
  // 图表数据导出
  exportChartData: (exportData) => api.post('/prediction/export-chart-data', exportData),
  
  // 使用模式分析
  getUsagePatterns: (startDate, endDate) => api.get('/prediction/usage-patterns', {
    params: { start_date: startDate, end_date: endDate }
  }),
  
  // 比利时节假日分析
  getBelgiumHolidayAnalysis: () => api.get('/prediction/belgium-holiday-analysis'),
  
  // 节假日SHAP分析
  getHolidayShapAnalysis: (startDate, endDate) => api.get('/prediction/holiday-shap-analysis', {
    params: {
      start_date: startDate,
      end_date: endDate
    }
  }),
  
  // 气象负荷相关性分析
  getWeatherLoadCorrelation: (startDate, endDate) => api.get('/prediction/weather-load-correlation', {
    params: {
      start_date: startDate,
      end_date: endDate
    }
  }),
  
  // 气象负荷时间序列数据 (30天)
  getWeatherLoadTimeSeries: (startDate, endDate) => api.get('/prediction/weather-load-time-series', {
    params: {
      start_date: startDate,
      end_date: endDate
    }
  }),
  
  // 15分钟粒度负荷对比分析
  getLoadComparison15min: (startDate, endDate) => api.get('/prediction/load-comparison-15min', {
    params: {
      start_date: startDate,
      end_date: endDate
    }
  }),
  
  // 15分钟粒度节假日vs非节假日负荷对比分析
  getHolidayComparison15min: (startDate, endDate) => api.get('/prediction/holiday-comparison-15min', {
    params: {
      start_date: startDate,
      end_date: endDate
    }
  }),
  
  // 气象影响分析
  getWeatherImpact: (targetDate) => api.get('/prediction/weather-impact', {
    params: { target_date: targetDate }
  }),
  
  // SHAP分析
  getShapAnalysis: (targetDate, timeRange = 24) => api.get('/prediction/shap-analysis', {
    params: { 
      target_date: targetDate,
      time_range: timeRange
    }
  }),
  
  // 数据质量统计
  getDataQualityStats: () => api.get('/prediction/data-quality-stats'),
  getDataSourcesInfo: () => api.get('/prediction/data-sources-info'),
  
  // 兼容旧版API
  getDailyPrediction: (date) => api.get('/prediction/daily', {
    params: { date_str: date }
  }),
  getAvailableDates: () => api.get('/prediction/available-dates'),
  getPredictionRange: (startDate, endDate) => api.get('/prediction/range', {
    params: { start_date: startDate, end_date: endDate }
  }),
  getErrorAnalysis: (startDate, endDate) => api.get('/prediction/error-analysis', {
    params: { start_date: startDate, end_date: endDate }
  }),
  // 误差分析相关API
  getErrorMetrics: () => api.get('/prediction/error-analysis/metrics'),
  getAnomalies: (threshold) => api.get('/prediction/error-analysis/anomalies', {
    params: { threshold }
  }),
  getSampleDetails: (sampleIndex) => api.get(`/prediction/error-analysis/sample-details/${sampleIndex}`),
  generateErrorReport: () => api.post('/prediction/error-analysis/generate-report'),
  
  // 预测摘要信息
  getPredictionSummary: () => api.get('/prediction/prediction-summary'),
  
  // 多模型并行预测
  getMultiModelPrediction: (params) => api.get('/prediction/multi-model-prediction', { params })
}

// 数据同步相关API
export const dataSyncAPI = {
  // 手动同步数据
  syncPowerloadData: () => api.post('/sync/powerload'),
  syncWeatherData: () => api.post('/sync/weather'),
  
  // 数据同步状态
  getSyncStatus: () => api.get('/data-sync/status'),
  
  // 批量数据同步
  syncDateRange: (params) => api.post('/data-sync/sync-daily', null, { params }),
  syncWeatherRange: (startDate, endDate) => api.post(`/data-sync/sync-weather/${startDate}/${endDate}`),
  syncLoadRange: (startDate, endDate) => api.post(`/data-sync/sync-load/${startDate}/${endDate}`),
  
  // 系统初始化
  initializeSystem: () => api.post('/data-sync/initialize-system'),
  
  // 智能数据检测
  checkDataAvailability: (date) => api.get('/data-sync/check-availability', {
    params: { date }
  }),
  
  // 一键更新数据
  syncAllData: () => api.post('/data-sync/sync-all')
}

// 后端连接检查API
export const backendAPI = {
  checkConnection: () => api.get('/data-sync/health'),
  getServerInfo: () => api.get('/data-sync/health')
}

// 模型训练相关API
export const modelTrainingAPI = {
  startTraining: (config) => api.post('/model/train', config),
  getTrainingStatus: () => api.get('/model/status'),
  stopTraining: () => api.post('/model/stop'),
  saveModel: () => api.post('/model/save'),
  exportResults: (exportData) => api.post('/model/export', exportData)
}

// 实时预测相关API
export const realTimePredictionAPI = {
  startPrediction: (config) => api.post('/prediction/realtime', config),
  getPredictionHistory: (startDate, endDate, modelType) => api.get('/prediction/history', {
    params: { 
      start_date: startDate, 
      end_date: endDate, 
      model_type: modelType 
    }
  }),
  comparePrediction: (targetDate) => api.get('/prediction/compare', {
    params: { target_date: targetDate }
  }),
  
  // 获取预测历史记录
  getPredictionHistory: (limit = 3) => api.get('/prediction/history', {
    params: { limit }
  })
}

// 数据集概览相关API
export const datasetAPI = {
  getOverview: () => api.get('/dataset/overview')
}

// 模型评估相关API
export const modelEvaluationAPI = {
  // 获取模型指标
  getMetrics: () => api.get('/model-evaluation/metrics'),
  
  // 获取模型对比数据
  getComparison: () => api.get('/model-evaluation/comparison'),
  
  // 获取模型排名
  getRanking: (accuracyWeight = 0.7, efficiencyWeight = 0.3) => api.get('/model-evaluation/ranking', {
    params: { accuracy_weight: accuracyWeight, efficiency_weight: efficiencyWeight }
  }),
  
  // 生成评估报告
  generateReport: () => api.get('/model-evaluation/report'),
  
  // 获取样本详情
  getSampleDetails: (sampleIndex) => api.get(`/model-evaluation/sample/${sampleIndex}`),
  
  // 获取异常样本
  getAnomalies: (threshold = 0.95) => api.get('/model-evaluation/anomalies', {
    params: { threshold }
  }),
  
  // 获取性能趋势
  getPerformanceTrends: () => api.get('/model-evaluation/performance-trends'),
  
  // 重新评估模型
  evaluateModels: () => api.post('/model-evaluation/evaluate'),
  
  // 获取最佳模型
  getBestModel: () => api.get('/model-evaluation/best-model')
}

export default api 